<?php

namespace App\Jobs;

use App\Libraries\Tools\ConstVar;
use App\Libraries\Tools\Msg;
use App\Models\Order\Order;
use App\Models\Shop\Shop;
use App\Models\Shop\ShopTransLog;
use App\Models\Shop\ShopWithdrawConfig;
use App\Models\User\Balance;
use App\Models\User\User;
use EasyWeChat\Foundation\Application;
use Illuminate\Support\Facades\DB;

class ShopTransJob extends Job
{


    protected $order_id;
    protected $owner_id;
    protected $shop_id;

    public function __construct($order_id, $owner_id, $shop_id)
    {
        $this->order_id = $order_id;
        $this->owner_id = $owner_id;
        $this->shop_id = $shop_id;
    }

    public function handle(Order $order, ShopTransLog $shopTransLog, User $user,
                           Balance $balance, ShopWithdrawConfig $config)
    {
        $config = $config->where('shop_id', $this->shop_id)->first();
        if(empty($config->allow_quick_trans)){
            return false;
        }

        $order = $order->where('id', $this->order_id)
            ->where('status', ConstVar::$ORDER_STATUS_SUCCESS)
            ->whereIn('type', [ConstVar::$ORDER_TYPE_TRANSFER_TO_SHOP, ConstVar::$ORDER_TYPE_COUPON])
            ->first();
        if(empty($order)){
            return false;
        }

        $real_amount = sprintf("%.2f", $order->total_amount * (1-$config->ratio));

        $shopTransLog->order_id = $this->order_id;
        $shopTransLog->owner_user_id = $this->owner_id;
        $shopTransLog->apply_amount = $order->total_amount;
        $shopTransLog->withdraw_amount = $real_amount;
        $shopTransLog->ratio = $config->ratio;
        $shopTransLog->comment = '未开始转';
        $shopTransLog->save();

        $owner = $user->where('user_id', $this->owner_id)->first();

        if($config->ratio >= 1 || $config->ratio < 0){
            $shopTransLog->comment = '店铺费率设置错误';
            $shopTransLog->save();
            return false;
        }

        DB::beginTransaction();
        try{
            switch($order->channel){
                case ConstVar::$ORDER_CHANNEL_ALIPAY:
                    if(empty($config->alipay_acc)){
                        $shopTransLog->comment = '店铺没有支付宝账号';
                        $shopTransLog->save();
                        return false;
                    }
                    if(empty($config->alipay_name)){
                        $shopTransLog->comment = '店铺没有支付宝真名';
                        $shopTransLog->save();
                        return false;
                    }
                    $aop = new \AopClient();
                    $aop->gatewayUrl = env('ALIPAY_GATEWAY');
                    $aop->appId = env('ALIPAY_APPID');
                    $aop->rsaPrivateKey = env('ALIPAY_RSA_PRIVATE_KEY');
                    $aop->format = "json";
                    $aop->charset = "UTF-8";
                    $aop->signType = "RSA2";
                    $aop->alipayrsaPublicKey = env('ALIPAY_RSA_PUBLISH_KEY');
                    $ali_request = new \AlipayFundTransToaccountTransferRequest ();
                    $ali_request->setBizContent("{" .
                        "\"out_biz_no\":\"".$shopTransLog->id."\"," .
                        "\"payee_type\":\"ALIPAY_LOGONID\"," .
                        "\"payee_account\":\"{$config->alipay_acc}\"," .
                        "\"amount\":\"{$real_amount}\"," .
                        "\"payer_show_name\":\"夜城\"," .
                        "\"payee_real_name\":\"{$config->alipay_name}\"," .
                        "\"remark\":\"企业转账\"" .
                        "  }");
                    $result = $aop->execute ($ali_request);
                    $responseNode = str_replace(".", "_", $ali_request->getApiMethodName()) . "_response";
                    $resultCode = $result->$responseNode->code;
                    if(!empty($resultCode)&&$resultCode == 10000){
                        $shopTransLog->comment = '成功';
                        $shopTransLog->status = 1;
                        $shopTransLog->save();
                    } else {
                        $shopTransLog->comment = '支付宝错误信息：'.$result->$responseNode->sub_msg;
                        $shopTransLog->save();
                    }
                    break;
                case ConstVar::$ORDER_CHANNEL_WECHAT:
                    if(empty($config->wechat_openid)){
                        $shopTransLog->comment = '店铺没有微信open_id';
                        $shopTransLog->save();
                        return false;
                    }
                    if(empty($config->wechat_name)){
                        $shopTransLog->comment = '店铺没有微信真名';
                        $shopTransLog->save();
                        return false;
                    }
                    $app = new Application([
                        'app_id' => env('WECHAT_APPID'),
                        'payment' => [
                            'merchant_id'        => env('WECHAT_PAYMENT_MERCHANT_ID'),
                            'key'                => env('WECHAT_PAYMENT_KEY'),
                            'cert_path'          => env('WECHAT_PAYMENT_CERT_PATH'),
                            'key_path'           => env('WECHAT_PAYMENT_KEY_PATH'),
                        ],
                    ]);
                    $merchantPay = $app->merchant_pay;
                    $merchantPayData = [
                        'partner_trade_no' => $shopTransLog->id, //随机字符串作为订单号，跟红包和支付一个概念。
                        'openid' => $config->wechat_openid, //收款人的openid
                        'check_name' => 'FORCE_CHECK',  //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
                        're_user_name'=>$config->wechat_name,     //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
                        'amount' => $real_amount * 100,  //单位为分
                        'desc' => '企业付款',
                        'spbill_create_ip' => '119.29.1.227',  //发起交易的IP地址
                    ];
                    $result = $merchantPay->send($merchantPayData);
                    if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                        $shopTransLog->comment = '成功';
                        $shopTransLog->save();
                    }else{
                        $shopTransLog->comment = '微信错误信息：'.$result->err_code_des;
                        $shopTransLog->save();
                    }
                    break;
                default:
                    return false;
            }
            $balance->add(//提现记录
                Msg::withdraw().'_'.Msg::withdraw(),
                $this->shop_id,
                $owner->user_id,
                ConstVar::$BALANCE_CHANNEL_BALANCE,
                $order->channel,
                ConstVar::$ORDER_TYPE_WITHDRAW,
                0,
                $order->total_amount,
                0,
                0,
                0,
                ConstVar::$BALANCE_STATUS_SUCCESS,
                ConstVar::$BALANCE_TYPE_SHOP,
                ConstVar::$BALANCE_TYPE_USER
            );
            Shop::where('shop_id', $this->shop_id)->decrement('balance', $order->total_amount);
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e);
        }
        DB::commit();
        return true;
    }
}
